<template>
  <view class="search-container">
    <!-- 搜索栏 -->
        <search-input
          v-model="keyword"
      :show-cancel="true"
      @confirm="handleSearch"
          @focus="handleFocus"
      @cancel="handleCancel"
        ></search-input>

    <!-- 搜索建议 -->
    <view class="suggestions" v-if="showSuggestions && suggestions.length > 0">
      <view
        class="suggestion-item"
        v-for="(item, index) in suggestions"
        :key="index"
        @tap="handleSuggestionSelect(item)"
      >
        <uni-icons type="search" size="14" color="#999"></uni-icons>
        <text>{{ item }}</text>
      </view>
    </view>

    <!-- 搜索历史和热门搜索 -->
    <view v-if="!showSuggestions && !showResults" class="initial-content">
    <!-- 搜索历史 -->
    <search-history
        v-if="searchHistory.length > 0"
      :history="searchHistory"
        @select="handleHistorySelect"
        @clear="clearHistory"
    ></search-history>

    <!-- 热门搜索 -->
      <view class="hot-search" v-if="hotProducts.length > 0">
        <view class="header">
          <text class="title">热门搜索</text>
        </view>
        <view class="hot-list">
          <view
            class="hot-item"
            v-for="(item, index) in hotProducts"
            :key="index"
            @tap="handleHotSelect(item.name)"
          >
            <text :class="['rank', index < 3 ? 'top' : '']">{{ index + 1 }}</text>
            <text class="name">{{ item.name }}</text>
          </view>
        </view>
      </view>

      <!-- 初始空状态 -->
      <view class="empty-state" v-if="searchHistory.length === 0 && hotProducts.length === 0">
        <image src="/static/images/search-empty.png" mode="aspectFit"></image>
        <text>输入关键词开始搜索</text>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view v-if="showResults" class="search-results">
      <waterfall-flow 
      :products="products"
        @item-click="handleProductClick"
      ></waterfall-flow>
      <uni-load-more :status="loadMoreStatus"></uni-load-more>
    </view>
  </view>
</template>

<script>
import SearchInput from '@/components/search/SearchInput.vue'
import SearchHistory from '@/components/search/SearchHistory.vue'
import WaterfallFlow from '@/components/common/WaterfallFlow.vue'

export default {
  components: {
    SearchInput,
    SearchHistory,
    WaterfallFlow
  },
  data() {
    return {
      keyword: '',
      showSuggestions: false,
      showResults: false,
      suggestions: [],
      searchHistory: [],
      hotProducts: [],
      products: [],
      loadMoreStatus: 'more',
      pageNum: 1,
      pageSize: 10,
      suggestionsTimer: null,
      loading: false
    }
  },
  onLoad(options) {
    // 如果有传入的关键词，直接执行搜索
    if (options && options.keyword) {
      this.keyword = decodeURIComponent(options.keyword)
      this.search()
    }
    this.loadInitialData()
  },
  methods: {
    // 加载初始数据
    async loadInitialData() {
      try {
        // 并行加载搜索历史和热门商品
        const [historyRes, hotProductsRes] = await Promise.all([
          this.$api.product.search.getHistory(10),
          this.$api.product.search.getHot({ limit: 10 })
        ])
        
        if (historyRes.code === 200) {
          this.searchHistory = historyRes.data || []
        }
        
        if (hotProductsRes.code === 200 && hotProductsRes.data) {
          this.hotProducts = hotProductsRes.data.map(item => ({
            id: item.id,
            name: item.name,
            mainImage: item.mainImage,
            price: item.price,
            sales: item.sales
          }))
        }
      } catch (error) {
        console.error('加载初始数据失败:', error)
      }
    },

    // 加载搜索建议
    async loadSuggestions(keyword) {
      if (!keyword) {
        this.suggestions = []
        this.showSuggestions = false
        return
      }

      try {
        const res = await this.$api.product.search.getSuggestions(keyword.trim(), 10)
        if (res.code === 200) {
          this.suggestions = res.data || []
          this.showSuggestions = this.suggestions.length > 0
        }
      } catch (error) {
        console.error('加载搜索建议失败:', error)
        this.suggestions = []
        this.showSuggestions = false
      }
    },

    // 处理搜索
    async handleSearch() {
      if (!this.keyword) {
        uni.showToast({
          title: '请输入搜索关键词',
          icon: 'none'
        })
        return
      }

      const trimmedKeyword = this.keyword.trim()
      if (!trimmedKeyword) {
        uni.showToast({
          title: '请输入有效的搜索关键词',
          icon: 'none'
        })
        return
      }

      // 记录搜索历史
      try {
        await this.$api.product.search.recordHistory(trimmedKeyword)
        // 更新本地搜索历史
        const historyRes = await this.$api.product.search.getHistory(10)
        if (historyRes.code === 200) {
          this.searchHistory = historyRes.data || []
        }
      } catch (error) {
        console.error('记录搜索历史失败:', error)
      }

      // 执行搜索
      this.search()
    },

    // 执行搜索
    async search() {
      if (!this.keyword) return

      this.loading = true
      this.showSuggestions = false
      this.showResults = true
      this.pageNum = 1
      this.products = []

      try {
        const res = await this.$api.product.search.simple({
          keyword: this.keyword.trim(),
          pageNum: this.pageNum,
          pageSize: Math.min(20, this.pageSize) // 限制每页数量
        })

        if (res.code === 200 && res.data) {
          this.products = res.data.records || []
          this.loadMoreStatus = this.products.length < this.pageSize ? 'noMore' : 'more'
          
          if (this.products.length === 0) {
              uni.showToast({
              title: '未找到相关商品',
              icon: 'none',
              duration: 2000
            })
          }
        } else {
          throw new Error(res.message || '搜索失败')
        }
      } catch (error) {
        console.error('搜索失败:', error)
        this.showResults = false
        uni.showToast({
          title: error.message || '搜索失败，请重试',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.loading = false
      }
    },

    // 加载更多
    async loadMore() {
      if (this.loading || this.loadMoreStatus === 'noMore') return

      this.loading = true
      this.pageNum++

      try {
        const res = await this.$api.product.search.simple({
          keyword: this.keyword.trim(),
          pageNum: this.pageNum,
          pageSize: Math.min(20, this.pageSize)
        })
        
        if (res.code === 200 && res.data) {
          const newProducts = res.data.records || []
          this.products = [...this.products, ...newProducts]
          this.loadMoreStatus = newProducts.length >= this.pageSize ? 'more' : 'noMore'
        }
      } catch (error) {
        console.error('加载更多失败:', error)
        this.pageNum--
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 清空搜索历史
    async clearHistory() {
      try {
        await this.$api.product.search.clearHistory()
        this.searchHistory = []
        uni.showToast({
          title: '已清空历史',
          icon: 'success'
        })
      } catch (error) {
        console.error('清空搜索历史失败:', error)
      }
    },

    // 处理搜索框获得焦点
    handleFocus() {
      this.showSuggestions = this.keyword.length > 0
      this.showResults = false
    },

    // 处理取消
    handleCancel() {
      uni.navigateBack()
    },

    // 处理搜索建议选择
    handleSuggestionSelect(keyword) {
      this.keyword = keyword
      this.search()
    },

    // 处理历史记录选择
    handleHistorySelect(keyword) {
      this.keyword = keyword
      this.search()
    },

    // 处理热门商品选择
    handleHotSelect(keyword) {
      if (!keyword) return
      this.keyword = keyword
      this.search()
    },

    // 处理商品点击
    handleProductClick(product) {
      const id = product.id || product.productId
      if (!id) return
      
      // 直接跳转到商品详情页，不再记录点击行为
      uni.navigateTo({
        url: `/pages/product/detail/index?id=${id}`
      })
    }
  },
  watch: {
    keyword(newVal) {
      // 清除之前的定时器
      if (this.suggestionsTimer) {
        clearTimeout(this.suggestionsTimer)
      }
      
      // 如果关键词为空，直接清空建议
      if (!newVal) {
        this.suggestions = []
        this.showSuggestions = false
        return
      }
      
      // 设置新的定时器，防抖处理
      this.suggestionsTimer = setTimeout(() => {
        this.loadSuggestions(newVal)
      }, 300)
    }
  },
  onReachBottom() {
    if (this.showResults) {
      this.loadMore()
    }
  }
}
</script>

<style lang="scss" scoped>
.search-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.initial-content {
  min-height: 400rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  background-color: #fff;

  image {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 30rpx;
  }

  text {
    font-size: 28rpx;
    color: #999;
  }
}

.suggestions {
  background-color: #fff;
  padding: 20rpx;

  .suggestion-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    font-size: 28rpx;
    color: #333;

    .uni-icons {
      margin-right: 12rpx;
    }
  }
}

.hot-search {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #fff;

  .header {
    margin-bottom: 20rpx;

    .title {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
    }
  }

  .hot-list {
    .hot-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;

      .rank {
        width: 40rpx;
        font-size: 28rpx;
        color: #999;
        text-align: center;

        &.top {
          color: #ff5500;
          font-weight: bold;
        }
      }

      .name {
    flex: 1;
    margin-left: 20rpx;
        font-size: 28rpx;
        color: #333;
      }
    }
  }
}

.search-results {
  min-height: 200rpx;
  padding: 20rpx;
  background-color: #fff;
}
</style> 